package com.gxs.waqas.localfolders.exif;

import java.io.File;
import java.io.IOException;
import java.nio.file.CopyOption;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Scanner;

import com.drew.imaging.ImageMetadataReader;
import com.drew.metadata.Metadata;
import com.drew.metadata.exif.ExifSubIFDDirectory;

public class ExifBasedOrganizer
{

	public static void main(String[] args)
	{
		try
		{
			String location = "S:\\Pictures and Videos\\ORGANIZED_CAMERA_PICTURES";
			// updateFolderNamesToMatchFormat(new File(location));
			// reportEmptyFolders(new File(location));
			organizePicturesIntoSubfoldersInAGivenLocation(new File("S:\\Pictures and Videos\\ORGANIZED_CAMERA_PICTURES\\2013-xx-xx-Abbus-Phone-Pictures"));
		} catch (Exception e)
		{
			e.printStackTrace();
		}
	}

	public static void main2(String[] args)
	{
		try
		{
			File file = new File("C:\\temp\\test.jpg");
			Metadata metadata = ImageMetadataReader.readMetadata(file);
			ExifSubIFDDirectory directory = metadata.getDirectory(ExifSubIFDDirectory.class);
			Date date = directory.getDate(ExifSubIFDDirectory.TAG_DATETIME_ORIGINAL);

			System.out.println(date);
		} catch (Exception e)
		{
			e.printStackTrace();
		}
	}

	public static void reportEmptyFolders(File location) throws IOException
	{
		File[] listOfFiles = location.listFiles();
		int count = 0;

		for (File file : listOfFiles)
		{

			if (file.isDirectory())
			{
				String[] children = file.list();

				if (children == null || children.length < 1)
				{
					System.out.println("Deleting: " + file.getAbsolutePath());
					Files.delete(FileSystems.getDefault().getPath(file.getAbsolutePath()));
				}
			}
		}

	}

	public static void organizePicturesIntoSubfoldersInAGivenLocation(File location) throws Exception
	{
		//
		// We are here becuase it's a jpg or jpeg file
		System.out.println("Provide the name of the suffix for subdirctories: ");
		Scanner scanner = new Scanner(System.in);
		String suffix = scanner.next();

		File[] files = location.listFiles();
		List<String>errors = new ArrayList<String>();
		Date date = null;
		for (File file : files)
		{
			if (file.isDirectory())
				continue;

			String fileExtension = file.getName().substring(file.getName().lastIndexOf(".")+1);

			if (fileExtension.equalsIgnoreCase("jpg") || fileExtension.equalsIgnoreCase("jpeg"))
			{
				try
				{
					Metadata metadata = ImageMetadataReader.readMetadata(file);
					ExifSubIFDDirectory directory = metadata.getDirectory(ExifSubIFDDirectory.class);
					date = directory.getDate(ExifSubIFDDirectory.TAG_DATETIME_ORIGINAL);

				}
				catch(Throwable e)
				{
					errors.add(file.getName() + ", " + e.getMessage());
					continue;
				}
				
				if(date == null)
				{
					errors.add(file.getName()  + ", Date was null" );
					continue;
				}

				SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd-");
				String folderName = formatter.format(date) + suffix;

				File subfolder = new File(location, folderName);
				if (subfolder.exists())
				{
					// okay
				} else
				{
					subfolder.mkdirs();
				}

				// Now move the file:
				File newFile = new File(subfolder, file.getName());
				System.out.println("File: " + file.getAbsolutePath() + " will be moved to: " + newFile.getAbsolutePath());
				Files.move(FileSystems.getDefault().getPath(file.getAbsolutePath()), FileSystems.getDefault().getPath(newFile.getAbsolutePath()), StandardCopyOption.REPLACE_EXISTING);
			}

		}
		
		Thread.sleep(2 * 1000);
		for(String error : errors)
		{
			System.err.println(error);
		}

	}

	public static void updateFolderNamesToMatchFormat(File location) throws IOException
	{
		File[] listOfFiles = location.listFiles();
		int count = 0;

		for (File file : listOfFiles)
		{

			if (file.isDirectory())
			{
				if (file.getName().matches("[0-9]{4}-[0-9]{2}-[0-9]{2}.*"))
				{
					// Good
				} else
				{
					count++;
					System.out.println(count + ": " + file.getName() + " does not match");
					System.out.println("\t\tEnter new name, (s) to skip");
					Scanner scanner = new Scanner(System.in);
					String newName = scanner.next();

					if (newName.equalsIgnoreCase("s"))
						continue;

					File newFile = new File(file.getParent(), newName);

					if (newFile.exists())
					{
						System.err.println(newFile.getName() + " already exists - adding - part 2 to it");
						newFile = new File(newFile.getParent(), newFile.getName() + "-part2");
					}
					Files.move(FileSystems.getDefault().getPath(file.getAbsolutePath()), FileSystems.getDefault().getPath(newFile.getAbsolutePath()),
							StandardCopyOption.REPLACE_EXISTING);
				}
			}
		}

	}

}
